/**
 * ----------------------------------------------------------------------------------
 *  集合类（带分页）
 * ----------------------------------------------------------------------------------
 * 依赖： jQuery, artTemplate
 * Created by zhanglihe on 15/7/8.
 * ----------------------------------------------------------------------------------
 * 接口格式：
 *      注意： 接口数据格式必须是：{ret: 状态码, data: [列表数据], _count: 数据总条数}
 *
 * ----------------------------------------------------------------------------------
 * 使用方法：
 *      var collection = new Collection({
 *          options: { 配置信息... },
 *          render: { 重写输出过程 },
 *          render_item: { 重写列表循环过程 },
 *
 *          //事件绑定
 *          event: {
 *              '.item-edit:click': function(item,e) {  //item就是当前行的数据项
 *                  ...
 *              },
 *
 *              //hover鼠标经过事件的写法
 *              '.item-hover:hover': [function(item,e){ .. }, function(item,e){ ... }]
 *          }
 *      }).fetch();
 *
 */

require.config(require_config);

define([
    'jquery',
    'template',
    'model'
], function ($, template, Model) {
    var Collection = function (options) {
        var defaults = {
            container: 'data-list',    //页面元素ID
            template: 'data-item',     //列表模板ID
            url: false,                 //数据API地址
            page_dom: 'pagination', //分页显示元素ID
            condition: {limit: 10},  //查询条件
            show_page: true,           //显示分页
            max_page: 10,            //显示最大分页数
            model: {}
        };
        var originalOptions = options || {};

        var extent = $.extend(true, {}, defaults, options);
        extent.original = originalOptions;

        $.extend(this, extent);

        this.initialize();

        return this;
    };
    var options_data = '';//用于，查询条件不一致时，页数从1开始，记录从0开始
    Collection.prototype = {
        initialize: function () {
            this.el = $('#' + this.container);
        },
        /** 请求API接口获取数据 */
        fetch: function () {
            if (this.url == '') {
                return false;
            }
            var _this = this;
            ////用于，查询条件不一致时，页数从1开始，记录从0开始
            var obj = _this.condition;
            if (obj) {
                var _params = '';
                for (var i in obj) {
                    if (i == 'offset') continue;
                    _params = _params + '&' + i + '=' + obj[i];
                }
                if (options_data != _params) {
                    options_data = _params;
                    _this.condition.offset = this.condition.offset = 0;
                    _this.page.current_page = this.page.current_page = 1;
                }
            }
            ////用于，查询条件不一致时，页数从1开始，记录从0开始   end
            $.ajax({
                'url': _this.url,
                'type': 'get',
                'async': true,
                'data': this.condition,
                'dataType': 'json',
                'success': function (result) {
                    if (typeof(result.code) !== 'undefined' && result.code == 0) {
                        _this.sync(result);
                    } else {
                        Alert({msg: result.msg, type: 'error'});
                    }
                    _this.callback(result);
                }, 'error': function () {
                    Alert({msg: '通信错误', type: 'error'});
                }
            });
        },

        /** 接口请求成功后执行 */
        callback: function () {
        },

        /** 数据加载成功时执行 */
        sync: function (result) {
            this.result = result;
            //是否显示分页
            if (this.show_page == true) {
                this.paginated();
            }
            //如果结果为空，显示空记录模板内容
            if (!this.result.data || (typeof this.result.data.length !== 'undefined' && this.result.data.length === 0)) {
                var empty_html = $('#empty-tpl').html();
                empty_html = empty_html == undefined ? '' : empty_html;
                $('#' + this.container).html(empty_html);
                return;
            }
            this.el.html('');   //清空列表容器
            this.models = {};    //清空models

            this.render();
        },

        render: function () {
            var _this = this;
            $.each(this.result.data, function (key, item) {
                _this.render_item(key, item);
            });
            return this;
        },
        /** 输出到页面 */
        render_item: function (key, item) {
            $.extend(this.model, {
                data: item,
                template: this.template
            });
            this.models[key] = new Model(this.model);
            this.models[key].create_element();
            this.el.append(this.models[key].el);
        },

        /** 重新加载数据并输出 */
        reload: function () {
            var _page = this.page.current_page ? this.page.current_page : 1;
            this.goto(_page);
        },

        /**
         * 列表刷新，保持当前参数，重新请求接口请输出
         */
        refresh: function () {
            this.fetch();
        },

        /** 分页配置 */
        page: {page_size: 10, current_page: 1},

        /** 分页输出，页数超过n页时只显示n页 */
        paginated: function () {
            //重置page_size
            this.page.page_size = this.condition.limit;
            var _this = this;
            var html = '<ul class="pagination">';
            html += '<li><a href="javascript:" class="prev_page">&laquo;</a></li>';
            if (this.result._count >= 0) {
                this.page.page_total = Math.ceil(this.result._count / this.page.page_size);
                if (this.page.page_total <= this.max_page) {
                    for (var i = 1; i <= this.page.page_total; i++) {
                        if (i == this.page.current_page) {
                            html += '<li class="active"><a href="javascript:">' + i + '</a></li>';
                        } else {
                            html += '<li><a href="javascript:" class="page" rel="' + i + '">' + i + '</a></li>';
                        }
                    }
                } else {
                    console.log('more than 10 pages');
                    var page_html = '';
                    var half = this.max_page / 2;
                    var _c = 0; //已输出页码总数
                    var _cl = 0; //左边起始页
                    var _cr = 0; //右边结束
                    /** 计算出左边起始页*/
                    if (this.page.current_page < half) {
                        _cl = 1;
                    } else {
                        if (this.page.current_page > (this.page.page_total - half)) {
                            _cl = this.page.page_total - this.max_page + 1;
                        } else {
                            _cl = this.page.current_page - half + 1;
                        }
                    }
                    /** 计算出右边起始页*/
                    _cr = _cl + this.max_page - 1;
                    for (var i = _cl; i <= _cr; i++) {
                        if (this.page.current_page == i) {
                            page_html = page_html + '<li class="active"><a href="javascript:">' + i + '</a></li>';
                        } else {
                            page_html = page_html + '<li><a href="javascript:" class="page" rel="' + i + '">' + i + '</a></li>';
                        }
                    }
                    /** 加上第一页*/
                    if (_cl > 1) {
                        page_html = '<li><a href="javascript:" class="page" rel="' + 1 + '">1...</a></li>' + page_html;
                    }
                    /** 加上最后一页*/
                    if (_cr < this.page.page_total) {
                        page_html = page_html + '<li><a href="javascript:" class="page" rel="' + this.page.page_total + '">...' + this.page.page_total + '</a></li>';
                    }
                    html += page_html;
                }
            } else {
                return false;
            }

            html += '<li><a href="javascript:" class="next_page">&raquo;</a></li><li><a href="javascript:">共 ' + this.page.page_total + ' 页 , ' + this.result._count + ' 条记录</a></li>';

            if (this.page.page_total <= 1) {
                html = '<ul class="pagination"><li><a href="javascript:">共 ' + this.page.page_total + ' 页 , ' + this.result._count + ' 条记录</a></li></ul>';
            }

            $('#' + this.page_dom).html(html);
            //绑定事件
            $('.page').on('click', function () {
                _this.goto(parseInt($(this).attr('rel')));
            });
            $('.prev_page').on('click', function () {
                _this.goto_prev();
            });
            $('.next_page').on('click', function () {
                _this.goto_next();
            });
        },

        /** 跳转到某页 */
        goto: function (page) {
            this.condition.offset = ((page - 1) * this.page.page_size);
            this.page.current_page = page;
            this.fetch();
        },

        /** 上一页 */
        goto_prev: function () {
            if (this.page.current_page > 1) {
                this.page.current_page--;
                this.condition.offset = ((this.page.current_page - 1) * this.page.page_size);
                this.fetch();
            }
        },

        /** 下一页 */
        goto_next: function () {
            if (this.page.current_page < this.page.page_total) {
                this.page.current_page++;
                this.condition.offset = ((this.page.current_page - 1) * this.page.page_size);
                this.fetch();
            }
        }

    };

    return Collection;

});